/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClientsGui.java
 *
 * Created on 6 juil. 2011, 21:24:09
 */
package app.views;

import app.App;
import app.events.ClientListener;
import app.events.ClientSelectedListener;
import app.events.eventobjects.ClientAddedEvent;
import app.events.eventobjects.ClientDeletedEvent;
import app.events.eventobjects.ClientUpdatedEvent;
import app.models.Client;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Ghost
 */
public class ClientsGui extends JPanel implements ListSelectionListener, 
        MouseListener, ActionListener, KeyListener, ClientListener {

    protected List<Client> clients = new ArrayList<Client>();
    
    protected Vector<String> fields;
    
    protected JPopupMenu popMenu;
    
    protected javax.swing.event.EventListenerList listenerList =
        new javax.swing.event.EventListenerList();
    
    private JLabel jLabel1;
    private JScrollPane jScrollPane1;
    private JToolBar toolbar;
    private JTextField txtSearch;
    private JMenuItem miEdit;
    private JMenuItem miDelete;
    private JMenuItem miSelect;
    private javax.swing.JButton btSearch;
    protected SimpleTable<Client> clientsTable;
    
    /** 
     * Creates new form ClientsGui 
     */
    public ClientsGui() {
        
        toolbar = new JToolBar();
        jLabel1 = new JLabel();
        txtSearch = new JTextField();
        jScrollPane1 = new JScrollPane();
        clientsTable = new SimpleTable<Client>();
        btSearch = new JButton();
        
        btSearch.setIcon(app.App.createIcon("resources/search.png"));
        btSearch.setFocusable(false);
        btSearch.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btSearch.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        
        //Popupmenu preparation
        popMenu = new JPopupMenu();
        miEdit = new JMenuItem("Editer", App.createIcon("resources/user_edit.png"));
        miEdit.addActionListener(this);
        popMenu.add(miEdit);
        miDelete = new JMenuItem("Supprimer", App.createIcon("resources/user_delete.png"));
        miDelete.addActionListener(this);
        popMenu.add(miDelete);
        miSelect = new JMenuItem("Selectionner", App.createIcon("resources/user_go.png"));
        miSelect.addActionListener(this);
        popMenu.add(miSelect);
        
        
        
        //gui preparation
        this.setLayout(new BorderLayout(5, 5));
        this.setPreferredSize(new Dimension(100, 200));
        //toolbar
        toolbar.setRollover(false);
        toolbar.setFloatable(false);
        txtSearch.addKeyListener(this);
        jLabel1.setText("Chercher :");
        toolbar.add(jLabel1);
        toolbar.add(txtSearch);
        toolbar.add(btSearch);
        add(toolbar, BorderLayout.PAGE_START);

        //table
        fields = new Vector<String>();
        fields.add("Nom");
        fields.add("Prenom");
        fields.add("Tel");
        fields.add("Email");
        
        clientsTable.setHeaders(fields);
        clientsTable.addMouseListener(this);
        add(clientsTable, BorderLayout.CENTER);
               
    }
    
    /**
     * Get the value of clients
     *
     * @return the value of clients
     */
    public List<Client> getClients() {
        return clients;
    }

    /**
     * Set the value of clients
     *
     * @param clients new value of clients
     */
    public void setClients(List<Client> clients) {
        this.clients = clients;
        clientsTable.addElements(clients);
    }

    /**
     * 
     * @param cli 
     */
    public void addClient(Client cli) {
        this.clients.add(cli);
        clientsTable.addElement(cli);
    }
    
    public void filter(String pat){
        if("".equals(pat)){
            clientsTable.setElements(this.clients);
        } else {
            List<Client> cls = new ArrayList<Client>();
            pat = pat.toLowerCase();
            for(Client c : this.clients){
                if(c.getNom().toLowerCase().contains(pat) ||
                        c.getPrenom().toLowerCase().contains(pat) ||
                        (c.getEmail() != null && c.getEmail().toLowerCase().contains(pat)) ||
                        (c.getTel() != null && c.getTel().toLowerCase().contains(pat))
                        ){
                    cls.add(c);
                }
            }
            clientsTable.setElements(cls);
        }
    }
    
    /**
     * Get the current selected client
     * @return Client the selected client or null if none selected
     */
    public Client getSelectedClient(){
        return clientsTable.getSelectedElement();
    }
    
    /**
     * 
     * @param listener 
     */
    public void addClientSelectedListener(ClientSelectedListener listener){
        listenerList.add(ClientSelectedListener.class, listener);
    }
    
    /**
     * 
     * @param listener 
     */
    public void removeClientSelectedListener(ClientSelectedListener listener){
        listenerList.remove(ClientSelectedListener.class, listener);
    }
        
    /**
     * 
     * @param cli 
     */
    void fireClientSelected(Client cli){
        //Tools.debug("Client Dialog a recu un evenement de selection " + cli);
        Object[] listeners = listenerList.getListenerList();
        // Each listener occupies two elements - the first is the listener class
        // and the second is the listener instance
        for (int i=0; i<listeners.length; i+=2) {
            if (listeners[i]==ClientSelectedListener.class) {
                ((ClientSelectedListener)listeners[i+1]).clientSelected(cli);
            }
        }
    }
    
    /**
     * 
     * @param e 
     */
    @Override
    public void valueChanged(ListSelectionEvent e) {
        /*if(!e.getValueIsAdjusting()){
            System.out.println(clients.get(clientsTable.getSelectedRow()));
        }*/
    }

    /**
     * 
     * @param e 
     */
    @Override
    public void mouseClicked(MouseEvent e) {
        if(e.getButton() == MouseEvent.BUTTON3) {
            Point p = e.getPoint();
            int row = clientsTable.rowAtPoint(p);
            clientsTable.setSelectedRow(row);
            popMenu.show(clientsTable, e.getX(), e.getY());
        }
        if(e.getClickCount() == 2){
            fireClientSelected(getSelectedClient());
        }
    }


    @Override public void mousePressed(MouseEvent e) {}

    @Override public void mouseReleased(MouseEvent e) {}

    @Override public void mouseEntered(MouseEvent e) {}

    @Override public void mouseExited(MouseEvent e) {}

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        
        if(source.equals(miSelect) || source.equals(miEdit) ){
            Client cli = getSelectedClient();
            if(cli != null){
                fireClientSelected(cli);
            } else {
                //@todo manage this error (no client selected)
            }
        } else if(source.equals(miDelete)){
            Client cli = getSelectedClient();
            String html = "<html>Êtes vous sur de vouloir "
                    + "supprimer: <br>"
                    + "<b>" +  cli.getNom() + " " + cli.getPrenom() + "</b>?"
                    + "<br>Il ne sera plus visible dans le catalogue"
                    + "<br><i>(Je rigole pas, il sera VRAIMENT supprimé...)</i></html>";
            JLabel text = new JLabel(html);
            int response = JOptionPane.showConfirmDialog(this, text, 
                    "Supprimer un client", JOptionPane.YES_NO_OPTION, 
                    JOptionPane.WARNING_MESSAGE);
            
            if(response == JOptionPane.YES_OPTION){               
                App.getInstance().getRegistre().removeClient(cli);
                App.displayMessage("Malheureusement, " + cli.getPrenom() + " " + 
                        cli.getNom() + " nous à quitter...\n\n Champagne?", App.MESSAGE_TYPE.INFO);
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {}

    @Override
    public void keyReleased(KeyEvent e) {
        String pattern = txtSearch.getText();
        filter(pattern);
    }

    @Override
    public void onClientAdded(ClientAddedEvent cae) {
        Client cli = cae.getClient();
        clients.add(cae.getClient());
        clientsTable.addElement(cae.getClient());
    }

    @Override
    public void onClientUpdated(ClientUpdatedEvent cue) {
        int id = clients.indexOf(cue.getOldClient());
        clients.set(id, cue.getNewClient());
        clientsTable.updateElement(cue.getOldClient(), cue.getNewClient());
    }

    @Override
    public void onClientDeleted(ClientDeletedEvent cde) {
        clients.remove(cde.getClient());
        clientsTable.removeElement(cde.getClient());
    }
    
}
